package cn.topcodes.tcsf.wechat.service;

import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.wxsdk.WXContext;
import cn.topcode.unicorn.wxsdk.base.Result;
import cn.topcode.unicorn.wxsdk.message.MessageInvoker;
import cn.topcode.unicorn.wxsdk.message.template.SendTemplateMessageResult;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMessage;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMp;
import cn.topcodes.tcsf.wechat.domain.entity.WechatPushLog;
import cn.topcodes.tcsf.wechat.domain.entity.WechatUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 微信消息 服务
 * @author unicorn
 * @date 2017-08-17 15:51:48
 */
@Service
public class WechatMessageServiceImpl extends GenericService<WechatMessage> implements WechatMessageService {

    private MessageInvoker invoker = WXContext.getMessageInvoker();

    @Autowired
    private WechatMpService wechatMpService;

    @Autowired
    private WechatUserService wechatUserService;

    @Autowired
    private WechatPushLogService wechatPushLogService;

    @Override
    @Transactional(readOnly = false)
    public SendTemplateMessageResult sendTemplateMessage(String mpId, String openId, String templateId, String url, Object data) {
        WechatPushLog wechatPushLog = new WechatPushLog();
        WechatUser wechatUser = wechatUserService.findByOpenId(openId);
        wechatPushLog.setToUser(wechatUser.getNickname() + "(" + openId + ")");
        wechatPushLog.setContent(JsonUtil.toJson(data));
        wechatPushLog.setTime(new Date());
        WechatMp wechatMp = wechatMpService.findWechatMpByMpId(mpId);
        wechatPushLog.setWechatMpId(wechatMp.getId());
        SendTemplateMessageResult result = invoker.sendTemplateMessage(mpId, openId, templateId, url, data);
        if (result.getErrcode() == 0) {
            wechatPushLog.setState(WechatPushLog.TYPE_TRUE);
            wechatPushLog.setReason("");
        } else {
            wechatPushLog.setState(WechatPushLog.TYPE_FALSE);
            wechatPushLog.setReason(result.getErrmsg());
        }
        wechatPushLogService.create(wechatPushLog);
        return result;
    }

    @Override
    public SendTemplateMessageResult sendTemplateMessage(String openId, String templateId, String url, Object data) {
        return this.sendTemplateMessage(wechatMpService.getDefaultMpId(), openId, templateId, url, data);
    }
}
